<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/18 12:37:09 $)
// $RCSfile: client_chat.php,v $ : $Revision: 1.19 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/livesupport/functions_livesupport.php");

$template->loadLanguageSection("livesupportclient");

$template->assign("randno", buildHash());

/**
* ###############################################
* Default frame loaded when user first clicks live support button
* ###############################################
*/
if ($eventaction == "startclientchat")
{
	$template->cache(array('defaultchatframeset', 'chathtmlheader'));
	// is proactive set?
	if ($_GET["proactive"] == PROACTIVE_FORCED || $_GET["proactive"] == PROACTIVE_REQUEST)
	{
		// Get the id
		$_proactive = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."visitorpulls` WHERE `visitorsessionid` = '". $dbCore->escape($_GET["sessionid"]) ."';");
		if ($_proactive["staffid"] != "")
		{
			// Super, we have a proper pull set.
			flushVisitorPulls($_GET["sessionid"]);

			$redirstaffid = $_proactive["staffid"];
			
			// Get any department to which staff or group is assigned to. : No need for this check (Mahesh Slaria).
	/*		if ($_SWIFT["staffcache"][$redirstaffid]["groupassigns"] == "1")
			{
				$_staffgroupid = $_SWIFT["staffcache"][$redirstaffid]["staffgroupid"];
			} else {
				$_staffgroupid = "0";
			}*/

			$_department = $dbCore->queryFetch("SELECT departments.departmentid FROM `". TABLE_PREFIX ."departments` AS departments LEFT JOIN `". TABLE_PREFIX ."staffassigns` AS staffassigns ON (staffassigns.departmentid = departments.departmentid) LEFT JOIN `". TABLE_PREFIX ."groupassigns` AS groupassigns ON (groupassigns.departmentid = departments.departmentid) WHERE staffassigns.staffid = '". $dbCore->escape($redirstaffid) ."';");
			// No department set?
			if ($_department["departmentid"] == "")
			{
				unset($redirstaffid);
			} else {
				$redirdepartmentid = $_department["departmentid"];
			}
		}
	}

	if ($redirstaffid != "")
	{
		header("location: index.php?_m=livesupport&_a=startformchat&sessionid=". urlencode($_GET["sessionid"]) ."&fullname=". urlencode(generateRandomVisitorName()) ."&email=&departmentid=".urlencode($redirdepartmentid)."&proactivestaffid=".urlencode($redirstaffid));
	} else {
		if (isStaffMonitorOnline($_GET["departmentid"]) == STATUS_ONLINE && $_GET["leavemessage"] != 1)
		{
			$template->assign("isstaffonline", "1");
		} else {
			$template->assign("isstaffonline", "0");
		}

		$template->assign("sessionid", $_GET["sessionid"]);
		$template->assign("departmentid", $_GET["departmentid"]);

		$template->assign("uefullname", urlencode($_GET["fullname"]));
		$template->assign("ueemail", urlencode($_GET["email"]));

		$template->assign("refreshinterval", $_SWIFT["settings"]["livesupport_clientchatrefresh"]*1000);
		echo $template->displayTemplate("chathtmlheader");
		echo $template->displayTemplate("defaultchatframeset");
	}


/**
* ###############################################
* The chat header frame, this one also holds almost all the chat handling functions
* ###############################################
*/
} else if ($eventaction == "chatheaderframe") {
	$template->cache(array('chathtmlheader', 'chatheaderframe'));

	headerNoCache();

	$template->assign("sessionid", $_GET["sessionid"]);
	$template->assign("chatsessionid", $_GET["chatsessionid"]);
	
	if (!empty($_GET["chatsessionid"]))
	{
		$template->assign("ischat", "true");
		$template->assign("clientfullname", htmlspecialchars($_GET["clientfullname"]));
	}

	$template->assign("refreshinterval", $_SWIFT["settings"]["livesupport_clientchatrefresh"]*1000);
	echo $template->displayTemplate("chathtmlheader");
	echo $template->displayTemplate("chatheaderframe");



/**
* ###############################################
* The chat footer frame, contains copyright notice and also displays "User is Typing" messages
* ###############################################
*/
} else if ($eventaction == "chatfooterframe") {
	$template->cache(array('chathtmlheader', 'chatfooterframe'));
	$template->assign("sessionid", $_GET["sessionid"]);

	echo $template->displayTemplate("chathtmlheader");
	echo $template->displayTemplate("chatfooterframe");	




/**
* ###############################################
* This one displays the online departments and also asks the user for username and password
* ###############################################
*/
} else if ($eventaction == "chatstartcontentframe") {
	$template->cache(array('chathtmlheader', 'chatcontentframe', 'departmentstatuscombo'));
	$template->assign("sessionid", $_GET["sessionid"]);

	require_once ("./modules/livesupport/functions_livesupport.php");

	$depresult = getDepartmentsStatus($_GET["departmentid"]);

	$template->assign("onlinedepartments", $depresult["online"]);
	$template->assign("offlinedepartments", $depresult["offline"]);
	$template->assign("departmentid", $_GET["departmentid"]);

	$template->assign("fullname", $_GET["fullname"]);
	$template->assign("email", $_GET["email"]);

		$template->assign("refreshinterval", $_SWIFT["settings"]["livesupport_clientchatrefresh"]*1000);
	echo $template->displayTemplate("chathtmlheader");
	echo $template->displayTemplate("chatcontentframe");



/**
* ###############################################
* Default CSS template handling, sends a headerCache() so it isnt called everytime by the browser
* ###############################################
*/
} else if ($eventaction == "chatcss") {
	$template->cache(array('clientcss'));
	header("Content-Type: text/css");
	headerCache();

	echo $template->displayTemplate("clientcss");




/**
* ###############################################
* The Main chat frameset, this is initiated AFTER the user submits chat info
* ###############################################
*/
} else if ($eventaction == "startformchat") {
	$template->cache(array('chatframeset', 'chathtmlheader'));

	$template->assign("sessionid", $_REQUEST["sessionid"]);

	if (trim($_REQUEST["proactivestaffid"]) != "")
	{
		$roundrobinstaffid = intval($_REQUEST["proactivestaffid"]);
		$isproactive = true;
	} else {
		$roundrobinstaffid = getRoundRobinStaff(intval($_REQUEST["departmentid"]));
		$isproactive = false;
	}

	$template->assign("uefullname", urlencode($_GET["fullname"]));
	$template->assign("ueemail", urlencode($_GET["email"]));

	if (!$roundrobinstaffid)
	{
		// Seems like user selected a department which has no staff online? Show him the Leave a Message form
		$template->assign("isstaffonline", "0");

		echo $template->displayTemplate("chathtmlheader");
		echo $template->displayTemplate("defaultchatframeset");
	} else {
		$departmentTitle = $departments->getDepartmentNameFromId($_REQUEST["departmentid"]);

		// Insert the chat object
		$userId = 0;

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."chatobjects` (`visitorsessionid`, `dateline`, `lastpostactivity`, `userpostactivity`, `staffpostactivity`, `userid`, `userfullname`, `useremail`, `staffid`, `staffname`, `chatstatus`, `transferfromid`, `transfertoid`, `transferstatus`, `transfertimeline`, `roundrobintimeline`, `roundrobinhits`, `departmentid`, `departmenttitle`, `chattype`, `ipaddress`, `isproactive`) VALUES('". $dbCore->escape($_REQUEST["sessionid"]) ."', '". DATENOW ."', '0', '0', '0', '". $dbCore->escape($userId) ."', '". $dbCore->escape($_REQUEST["fullname"]) ."', '". $dbCore->escape($_REQUEST["email"]) ."', '". $dbCore->escape($roundrobinstaffid) ."', '". $dbCore->escape($_SWIFT["staffcache"][$roundrobinstaffid]["fullname"]) ."', '". CHAT_INCOMING ."', '0', '0', '0', '0', '". DATENOW ."', '0', '". $dbCore->escape($_REQUEST["departmentid"]) ."', '". $dbCore->escape($departmentTitle) ."', '". CHAT_CLIENT ."', '". $dbCore->escape($_SERVER["REMOTE_ADDR"]) ."', '". iif($isproactive==true, "1", "0") ."');");

		$chatObjectId = $dbCore->lastInsertId();

		$sessionid = $session->insertSession(SESSION_CHAT, $chatObjectId);
		
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."chatdata` (`chatobjectid`, `contents`) VALUES('". $dbCore->escape($chatObjectId) ."', '". $dbCore->escape(serialize(array())) ."');");
		
		$template->assign("chatsessionid", $sessionid);
		$template->assign("clientfullname", urlencode($_REQUEST["fullname"]));

		$template->assign("refreshinterval", $_SWIFT["settings"]["livesupport_clientchatrefresh"]*1000);
		echo $template->displayTemplate("chathtmlheader");
		echo $template->displayTemplate("chatframeset");
	}



	
/**
* ###############################################
* Chat Post Frame, the one that holds the text area
* ###############################################
*/
} else if ($eventaction == "clientchatpostframe") {
	$template->cache(array('chatpostframe', 'chathtmlheader'));
	$template->assign("chatsessionid", $_GET["chatsessionid"]);
	$template->assign("sessionid", $_GET["sessionid"]);

	echo $template->displayTemplate("chathtmlheader");
	echo $template->displayTemplate("chatpostframe");




/**
* ###############################################
* Main chat content frame after chat has started
* ###############################################
*/
} else if ($eventaction == "chatstartedcontentframe") {
	$template->cache(array('chatstartedcontentframe', 'chathtmlheader'));
	$template->assign("chatsessionid", $_GET["chatsessionid"]);
	$template->assign("sessionid", $_GET["sessionid"]);
	require_once ("./modules/livesupport/functions_livesupport.php");
	if ($_SWIFT["settings"]["livesupport_displayclientchatqueue"] == 1)
	{
		// Get the total number of other people in queue
		$totalqueue = getTotalPendingChatQueue(array($_GET["sessionid"]));

		if ($totalqueue > 0)
		{
			$template->assign("peopleaheadqueue", sprintf($_SWIFT["language"]["peopleaheadinqueue"], $totalqueue));
		}			
	}

	echo $template->displayTemplate("chathtmlheader");
	echo $template->displayTemplate("chatstartedcontentframe");


/**
* ###############################################
* Processing of message submitted by client
* ###############################################
*/
} else if ($eventaction == "submitclientchatmsg")
{
	if (trim($_GET["msg"]) != "")
	{
		require_once ("./modules/livesupport/functions_livesupport.php");

		submitChatMessage($_GET["chatsessionid"], MESSAGE_CLIENT, base64_encode(preg_replace('/&amp;#(x[a-f0-9]+|[0-9]+);/i', '&#$1;', htmlspecialchars(unescapeJSUnicode($_GET["msg"])))), true);
	}


/**
* ###############################################
* END VISITOR CHAT
* ###############################################
*/
} else if ($eventaction == "endvisitorchat") {
	$_chatobject = getChatObjectFromSession($_GET["chatsessionid"]);

	if (trim($_chatobject["chatobjectid"]) != "")
	{
		require_once ("./modules/livesupport/functions_livesupport.php");
		endChat($_chatobject["chatobjectid"]);
	}

	

/**
* ###############################################
* Visitor is Typing
* ###############################################
*/
} else if ($eventaction == "visitortyping") {
	if (trim($_REQUEST["chatsessionid"]) != "" && $_SWIFT["settings"]["livesupport_enableuseristyping"] == 1)
	{
		$_chatobject = getChatObjectFromSession($_REQUEST["chatsessionid"]);

		if ($_chatobject["chatobjectid"] != "")
		{
			submitChatAction($_chatobject["chatobjectid"], SUBMIT_CLIENT, ACTION_TYPING, $_chatobject["userfullname"]);
		}
	}
}

?>